package mushystuff.dtb.core.service.pojo;

import java.util.List;

import mushystuff.dtb.core.dao.ProductDAO;
import mushystuff.dtb.core.dao.SprintDAO;
import mushystuff.dtb.core.dao.UserStoryDAO;
import mushystuff.dtb.core.model.Product;
import mushystuff.dtb.core.model.Sprint;
import mushystuff.dtb.core.model.UserStory;
import mushystuff.dtb.core.service.ProductService;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public final class ProductServiceImpl implements ProductService {

    @SuppressWarnings("unused")
    private Log log = LogFactory.getLog(this.getClass());

    private ProductDAO productDAO;
    
    private UserStoryDAO userStoryDAO;
    
    private SprintDAO sprintDAO;

    @Required
    public void setProductDAO(ProductDAO productDAO) {
        this.productDAO = productDAO;
    }
    
    @Required
    public void setUserStoryDAO(UserStoryDAO userStoryDAO) {
        this.userStoryDAO = userStoryDAO;
    }
    
    @Required
    public void setSprintDAO(SprintDAO sprintDAO) {
        this.sprintDAO = sprintDAO;
    }

    @Override
    public Product createUpdateProduct(Product product) {
        if (StringUtils.isEmpty(product.getName())) {
            throw new IllegalArgumentException("Name must be set");
        }
        return productDAO.persistProduct(product);
    }

    @Override
    public Product getProduct(long productId) {
        return productDAO.getProduct(productId);
    }

    @Override
    public List<Product> getAllProducts() {
        return productDAO.getAllProducts();
    }

    @Override
    public void addUserStoryToBacklog(Product product, UserStory userStory) {
        userStory.setProduct(product);
        product.getBacklog().add(userStory);
        productDAO.persistProduct(product);
    }

    @Override
    public void addSprint(Product product, Sprint sprint) {
        sprint.setProduct(product);
        product.getSprints().add(sprint);
        productDAO.persistProduct(product);
    }

    @Override
    public void removeUserStoryFromBacklog(long userStoryId) {
        UserStory userStory = userStoryDAO.getUserStory(userStoryId);
        Product product = userStory.getProduct();
        product.getBacklog().remove(userStory);
        productDAO.persistProduct(product);
    }

}
